//
//  YFAccessTokenModel.swift
//  YFSwiftWeibo
//
//  Created by tsaievan on 2017/8/31.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit

class YFAccessTokenModel: NSObject {
    
    fileprivate let accountPath: NSString = "account.json"
    
    /// 访问令牌
    var access_token: String? //= "2.00Fn5ISBqy6h5E1c4ff02e74UWwmGD"
    
    /// 过期时间
    /// 开发者是5年, 每次登录都是5年
    /// 普通用户登录是3天, 从第一次登录开始算, 这个时间会递减
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    ///< 过期时间
    var expiresDate: Date?
    
    ///< 用户昵称
    var screen_name: String?
    
    ///< 用户头像
    var avatar_large: String?
    
    /// 用户的uid
    var uid: String?
    
    /// 重写description方法
    override var description: String {
        return yy_modelDescription()
    }
    
    /// 重写init方法
    override init() {
        super.init()
        guard let path = accountPath.hm_documentDirectory,
            let data = NSData(contentsOfFile: path),
            let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String : Any] else {
                return
        }
        ///< 使用字典设置属性
        ///< 用户是否登录的关键代码!
        yy_modelSet(with: dict ?? [:])
        
        ///< 测试token过期
//        expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("账户过期")
            access_token = nil
            uid = nil
            try? FileManager.default.removeItem(atPath: path)
        }
        
       
        print("\(self)")
    }
}

extension YFAccessTokenModel {
    func saveAccount() {
        ///< 模型转字典
        var accountDict = self.yy_modelToJSONObject() as? [String : Any] ?? [:]
        
        ///< 字典去掉一个key
        accountDict.removeValue(forKey: "expires_in")
        
        ///< 存储路径
        guard let path = accountPath.hm_documentDirectory,
            ///< Json序列化
            let accountData = try? JSONSerialization.data(withJSONObject: accountDict, options: []) as NSData
            else {
                return
        }
        accountData.write(toFile: path, atomically: true)
        print("用户登录模型存储的路径为:\(path)")
    }
}
